using Microsoft.Extensions.Options;
using MiniTheme.Models;
using MiniTheme.Services.Interfaces;
using Newtonsoft.Json.Linq;
using System.IO;

namespace MiniTheme.Services;

public class ConfigService : IConfigService
{
    private readonly IOptionsMonitor<AppSettings> _appSettings;
    private readonly string _configFilePath;

    public ConfigService(IOptionsMonitor<AppSettings> appSettings)
    {
        _appSettings = appSettings;
        // 配置文件路径(exe目录下)
        _configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
    }
    public string GetThemeMode() => _appSettings.CurrentValue.ThemeMode; 
    public string GetLanguage() => _appSettings.CurrentValue.Language;
    public void SetThemeMode(string themeMode)
    {   
        //"ThemeMode"字符串，与配置文件的key对应
        UpdateAppSetting(nameof(AppSettings.ThemeMode), themeMode);
    }
    public void SaveLanguage(string languageCode)
    {
        //"Language"字符串，与配置文件的key对应
        UpdateAppSetting(nameof(AppSettings.Language), languageCode);
    }
    private void UpdateAppSetting(string key, string value)
    {
        try
        {   
            // 读取或创建JSON内容
            var json = File.Exists(_configFilePath) ? File.ReadAllText(_configFilePath) : "{}";
            // 将json字符串转换成一个 JObject
            var jObject = JObject.Parse(json);
            // JObject就像一个 Dictionary<key, value>，它允许你动态地、按键名Key来读取和修改JSON属性
            jObject[AppSettings.SectionName] ??= new JObject();
            //{"AppSettings": {"ThemeMode": "Auto","Language": "zh-CN" }}
            // 只修改特定的键值对，从配置文件读取的不需要修改的还在
            jObject[AppSettings.SectionName]![key] = value;
            //Formatting.Indented是一个格式化选项，它使输出的JSON字符串是有缩进和换行，而不是压缩成一行
            File.WriteAllText(_configFilePath, jObject.ToString(Newtonsoft.Json.Formatting.Indented));
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error updating config: {ex.Message}");
        }
    }
}

